package com.lydms.web;

import com.lydms.common.ApiResult;
import com.lydms.service.WordDeleteService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 删除服务
 */
@RestController
@RequestMapping("/delete")
public class WordDeleteController {
    private static final Logger logger = LogManager.getLogger(WordDeleteController.class);

    @Autowired
    private WordDeleteService wordDeleteService;


    /**
     * 根据ID进行删除
     *
     * @param en
     * @return
     */
    @RequestMapping(value = "/id", method = {RequestMethod.POST})
    public ApiResult deleteID(@RequestBody Map<String, Object> en) {
        logger.info("englishId: {}, english: {}, chinese: {}, remark: {}",
                en.get("englishId"), en.get("english"), en.get("chinese"), en.get("remark"));

//        1、入参的校验
        Integer englishId = null;
        if (en.get("englishId") != null) {
            englishId = Integer.parseInt((String) en.get("englishId"));
        }
        if (englishId == null) {
            return ApiResult.fail(105, "请传入英语单词");
        }

//        2、根据英语删除
        boolean result = wordDeleteService.deleteID(englishId);

//        3、返回值判断
        if (!result) {
            logger.info("删除:{}失败", englishId);
            return ApiResult.fail(103, "删除失败");
        }
        logger.info("删除:{}成功", englishId);
        return ApiResult.succ(englishId);
    }


    /**
     * 根据英文进行删除
     *
     * @param en
     * @return
     */
    @RequestMapping(value = "/english", method = {RequestMethod.POST})
    public ApiResult deleteEnglish(@RequestBody Map<String, Object> en) {
        logger.info("englishId: {}, english: {}, chinese: {}, remark: {}",
                en.get("englishId"), en.get("english"), en.get("chinese"), en.get("remark"));

//        1、入参的校验
        String english = null;
        if (en.get("english") != null) {
            english = (String) en.get("english");
        }
        if (StringUtils.isBlank(english)) {
            return ApiResult.fail(105, "请传入英语单词");
        }

//        2、根据英语删除
        boolean result = wordDeleteService.deleteEnglish(english);

//        3、返回值判断
        if (!result) {
            logger.info("删除:{}失败", english);
            return ApiResult.fail(103, "删除失败");
        }
        logger.info("删除:{}成功", english);
        return ApiResult.succ(english);
    }


    /**
     * 测试能否调用成功
     */
    @RequestMapping(value = "/test", method = {RequestMethod.POST})
    public ApiResult test() {
        return ApiResult.succ("调用成功");
    }

}


